package com.jinzhi.jzweb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.ShiroUtils;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzweb.dao.JazOrderTakingDao;
import com.jinzhi.jzweb.domain.JazOrderTakingDO;
import com.jinzhi.jzweb.domain.JazSysProjectDO;
import com.jinzhi.jzweb.domain.JazUserAuntDO;
import com.jinzhi.jzweb.domain.param.UserDemanDQuery;
import com.jinzhi.jzweb.domain.vo.JazUserDemandVO;
import com.jinzhi.jzweb.domain.vo.userAunt.UserVO;
import com.jinzhi.jzweb.service.JazSysProjectService;
import com.jinzhi.jzweb.service.JazUserAuntService;
import com.jinzhi.sys.dao.UserDao;
import org.springframework.stereotype.Service;

import com.jinzhi.jzweb.dao.JazUserDemandDao;
import com.jinzhi.jzweb.domain.JazUserDemandDO;
import com.jinzhi.jzweb.service.JazUserDemandService;
import com.jinzhi.common.base.CoreServiceImpl;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2023-04-18 09:33:30 | Long</small>
 */
@Service
public class JazUserDemandServiceImpl extends CoreServiceImpl<JazUserDemandDao, JazUserDemandDO> implements JazUserDemandService {

    private final JazUserDemandDao jazUserDemandDao;

    private final UserDao userDao;

    private final JazUserAuntService jazUserAuntService;

    private final JazOrderTakingDao jazOrderTakingDao;

    /**
     * 项目类型
     */
    private final JazSysProjectService jazSysProjectService;

    public JazUserDemandServiceImpl(JazUserDemandDao jazUserDemandDao, UserDao userDao, JazUserAuntService jazUserAuntService, JazOrderTakingDao jazOrderTakingDao, JazSysProjectService jazSysProjectService) {
        this.jazUserDemandDao = jazUserDemandDao;
        this.userDao = userDao;
        this.jazUserAuntService = jazUserAuntService;
        this.jazOrderTakingDao = jazOrderTakingDao;
        this.jazSysProjectService = jazSysProjectService;
    }

    @Override
    public JazUserDemandVO selectDemandDetail(Long id) {
        return jazUserDemandDao.selectDemandDetail(id);
    }

    @Override
    public Page<JazUserDemandVO> selectAll(JazUserDemandVO jazUserDemandVO, int current, int size) {
        Page<JazUserDemandVO> page = new Page<>(current, size);
        List<JazUserDemandVO> jazUserOrderVOS = jazUserDemandDao.selectAll(page, jazUserDemandVO);
        return page.setRecords(jazUserOrderVOS);
    }

    /**
     * 多条件分页查询用户需求列表
     * @param userDemanDQuery
     * @return
     */
    @Override
    public Page<JazUserDemandDO> getUserDemandPage(UserDemanDQuery userDemanDQuery) {
        //查询用户需求
        Page<JazUserDemandDO> page = new Page<>(
                Optional.of(userDemanDQuery.getCurr()).orElse(1),
                Optional.of(userDemanDQuery.getPageSize()).orElse(10));
        Wrapper wrapper  = new EntityWrapper()
                .eq("demand_source",1)
                .eq(userDemanDQuery.getAuditStatus()!=null,"audit_status",userDemanDQuery.getAuditStatus())
                .like(StringUtil.notEmpty(userDemanDQuery.getName()),"user_name",userDemanDQuery.getName())
                .orderBy("update_time",false);
        Page<JazUserDemandDO> jdemands =  selectPage(page,wrapper);
        //查询项目类型
        List<Long> projectIds = jdemands.getRecords().stream().filter(a -> Objects.nonNull(a.getProjectId())).
                map(JazUserDemandDO::getProjectId).distinct().collect(Collectors.toList());
        if(ObjectUtils.isEmpty(projectIds)){
            return jdemands;
        }
        List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projectIds));
        jdemands.getRecords().forEach(a-> jazSysProjectDOS.forEach(b->{
            if(Objects.nonNull(a.getProjectId())) {
                if (Objects.equals(a.getProjectId(), b.getId())) {
                    a.setProjectName(b.getName());
                }
            }
        }));
        return jdemands;
    }

    @Override
    public JazUserDemandDO getUserDemandById(Long id) {
        JazUserDemandDO jdemand =  selectById(id);
        if (jdemand == null) {
            return null;
        }

        StringBuffer buffer = new StringBuffer();
        if (StringUtil.notEmpty(jdemand.getProvince())){
            buffer.append(jdemand.getProvince());
        }
        if (StringUtil.notEmpty(jdemand.getCity())){
            buffer.append(jdemand.getCity());
        }
        if (StringUtil.notEmpty(jdemand.getDistrict())){
            buffer.append(jdemand.getDistrict());
        }
        if (StringUtil.notEmpty(jdemand.getAddress())){
            buffer.append(jdemand.getAddress());
        }
        jdemand.setAddress(buffer.toString());

        // 查询接单的阿姨信息
        // 阿姨信息
        List<UserVO> list = new ArrayList<>();

        // 判断是否有阿姨进行接单
        if (jdemand.getStatus() == 2 ){
            // 查询临时表 获取接单阿姨的信息
            List<JazOrderTakingDO> jazOrderTakingDOS = jazOrderTakingDao.selectList(new EntityWrapper<JazOrderTakingDO>().eq("demand_id", jdemand.getId()));
            if (jazOrderTakingDOS.size() <=0){
                return jdemand;
            }
            // 获取接单阿姨的用户id
            List<Long> userIds = jazOrderTakingDOS.stream().map(JazOrderTakingDO::getInviteeId).collect(Collectors.toList());
            //查询阿姨信息
            List<UserDO> userDOList = userDao.selectBatchIds(userIds);
            if (userDOList.size()<=0){
                return null;
            }
            // 循环赋值
            userDOList.forEach(userDO -> {
                UserVO userVO = new UserVO();
                userVO.setSysUserid(userDO.getId());
                userVO.setName(userDO.getName());
                userVO.setMobile(userDO.getOrderPhone());
                userVO.setSex(userDO.getSex());
                userVO.setAge(userDO.getAge());
                userVO.setEducation(userDO.getEducation());
                // 查询月嫂信息
                JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(new EntityWrapper<JazUserAuntDO>().eq("sys_userid", userDO.getId()));
                if (jazUserAuntDO != null){
                    userVO.setWorkExperience(jazUserAuntDO.getWorkExperience());
                    userVO.setExperience(jazUserAuntDO.getExperience());
                    userVO.setInchPhoto(jazUserAuntDO.getInchPhoto());
                    // 查询月嫂类型
                    if(StringUtil.notEmpty(jazUserAuntDO.getProjectId())){
                        String[] projects = jazUserAuntDO.getProjectId().split(",");
                        List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projects));
                        userVO.setProjectName(jazSysProjectDOS.stream().map(JazSysProjectDO::getName).collect(Collectors.joining(",")));
                    }
                }
                list.add(userVO);
            });
        }

        jdemand.setUserVOList(list);

        //查询项目类型
        JazSysProjectDO jazSysProjectDO = Optional.ofNullable(jazSysProjectService.selectById(jdemand.getProjectId())).orElse(new JazSysProjectDO());
        jdemand.setProjectName(jazSysProjectDO.getName());
        return jdemand;
    }


    /**
     * 后台-根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public Result<JazUserDemandDO> selectDemandById(Long id) {
        JazUserDemandDO jazUserDemandDO = this.selectById(id);
        if (jazUserDemandDO == null){
            return null;
        }

        // 阿姨信息
        List<UserVO> list = new ArrayList<>();

        // 判断是否有阿姨进行接单
        if (jazUserDemandDO.getStatus() == 2 ){
            // 查询临时表 获取接单阿姨的信息
            List<JazOrderTakingDO> jazOrderTakingDOS = jazOrderTakingDao.selectList(new EntityWrapper<JazOrderTakingDO>().eq("demand_id", jazUserDemandDO.getId()));
            if (jazOrderTakingDOS.size() <=0){
                return Result.fail();
            }
            // 获取接单阿姨的用户id
            List<Long> userIds = jazOrderTakingDOS.stream().map(JazOrderTakingDO::getInviteeId).collect(Collectors.toList());
            //查询阿姨信息
            List<UserDO> userDOList = userDao.selectBatchIds(userIds);
            if (userDOList.size()<=0){
                return null;
            }
            // 循环赋值
            userDOList.forEach(userDO -> {
                UserVO userVO = new UserVO();
                userVO.setSysUserid(userDO.getId());
                userVO.setName(userDO.getName());
                userVO.setMobile(userDO.getOrderPhone());
                userVO.setSex(userDO.getSex());
                userVO.setAge(userDO.getAge());
                userVO.setEducation(userDO.getEducation());
                // 查询月嫂信息
                JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(new EntityWrapper<JazUserAuntDO>().eq("sys_userid", userDO.getId()));
                if (jazUserAuntDO != null){
                    userVO.setWorkExperience(jazUserAuntDO.getWorkExperience());
                    userVO.setExperience(jazUserAuntDO.getExperience());
                    userVO.setInchPhoto(jazUserAuntDO.getInchPhoto());
                    // 查询月嫂类型
                    if(StringUtil.notEmpty(jazUserAuntDO.getProjectId())){
                        String[] projects = jazUserAuntDO.getProjectId().split(",");
                        List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projects));
                        userVO.setProjectName(jazSysProjectDOS.stream().map(JazSysProjectDO::getName).collect(Collectors.joining(",")));
                    }
                }
                list.add(userVO);
            });
        }
        //查询项目类型
        JazSysProjectDO jazSysProjectDO = Optional.ofNullable(jazSysProjectService
                .selectById(jazUserDemandDO.getProjectId())).orElse(new JazSysProjectDO());
        jazUserDemandDO.setProjectName(jazSysProjectDO.getName());

        // 阿姨信息存入
        jazUserDemandDO.setUserVOList(list);

        return Result.ok(jazUserDemandDO);
    }

    /**
     * 新增后台需求
     *
     * @param jazUserDemandDO
     * @return
     */
    @Override
    public Result<String> insertDemand(JazUserDemandDO jazUserDemandDO) {
        if (jazUserDemandDO==null) {
            return Result.fail();
        }
        // 获取当前登录的用户
        UserDO sysUser = ShiroUtils.getSysUser();
        if (sysUser==null) {
            return Result.fail("请先登录后,在进行新增!");
        }
        jazUserDemandDO.setSysUserid(sysUser.getId());
        if (StringUtil.notEmpty(sysUser.getUsername())){
            jazUserDemandDO.setUserName(sysUser.getUsername());
        }else {
            jazUserDemandDO.setUserName(sysUser.getNickname());
        }
        if (StringUtil.notEmpty(sysUser.getMobile())){
            jazUserDemandDO.setOrderPhone(sysUser.getMobile());
        }
        // 设置后台需求来源
        jazUserDemandDO.setDemandSource(2);
        jazUserDemandDO.setAuditResult(0);
        jazUserDemandDO.setAuditStatus(1);
        jazUserDemandDO.setShowStatus(0);
        jazUserDemandDO.setIsSign(0);
        boolean insert = this.insert(jazUserDemandDO);

        return insert?Result.ok():Result.fail();
    }

    /**
     * 修改后台需求
     *
     * @param jazUserDemandDO
     * @return
     */
    @Override
    public Result<String> updateDemand(JazUserDemandDO jazUserDemandDO) {
        if (jazUserDemandDO==null) {
            return Result.fail();
        }
        JazUserDemandDO backgroundDO = this.selectById(jazUserDemandDO.getId());
        if (backgroundDO==null) {
            return Result.fail();
        }
        // 设置参数
        backgroundDO.setTitle(jazUserDemandDO.getTitle());
        backgroundDO.setProjectId(jazUserDemandDO.getProjectId());
        backgroundDO.setSex(jazUserDemandDO.getSex());
        backgroundDO.setResidentHome(jazUserDemandDO.getResidentHome());
        backgroundDO.setSalary(jazUserDemandDO.getSalary());
        backgroundDO.setWorkDate(jazUserDemandDO.getWorkDate());
        backgroundDO.setEndDate(jazUserDemandDO.getEndDate());
        backgroundDO.setAddress(jazUserDemandDO.getAddress());
        backgroundDO.setRemark(jazUserDemandDO.getRemark());

        boolean b = this.updateById(backgroundDO);

        return b?Result.ok():Result.fail();
    }
}
